#!/usr/bin/env bash

source ../../lib/shell/env.sh
source ./nvme_fio.sh

function fio_test_on(){
    local timeout=${1:-60} #60s
    FIO_NUMJOBS=1
    FIO_RUNTIME=$timeout
    echo "=================================="
    echo "Start nvme fio test"
    nvme_fio_test
    [ $? -eq 0 ] && return 0 || return 1
}

function fio_test_off(){
    local timeout=${1:-60}
    local pid=$(pidof fio)
    [ -n "$pid" ] && kill -9 $pid
    echo -e "\nStop nvme fio test keep ${timeout}s."
    sleep $timeout
}

# # # # # # # # main # # # # # # # #
stress_nvme_env 5 $RUNTIME
get_nvme_free_disk
if [ $? -ne 0 ];then
    echo "failed to get nvme free disk!"
    test_fail
else
    for nd in ${NVME_FREE_DISK[*]};do
        has_trim "${nd##*/}"
        [ $? -ne 0 ] && echo "Warning: $nd do not have trim!"
    done
fi

cur_time_diff=0
for ((i=1;i<=$RUNTIME;i+=$cur_time_diff));do
    cur_time=$(date +%s -d "$(date "+%F %H:%M:%S")")
    echo -e "\n[NVMe fio dynamic load test--->$i]"
    fio_test_on 60
    [ $? -ne 0 ] && test_fail "Error: failed to nvme fio test"
    fio_test_off 60
    [ $? -ne 0 ] && test_fail "Error: failed to nvme fio test"

    cur_time_diff=$(($(date +%s -d "$(date "+%F %H:%M:%S")") - $cur_time))
    [ $(($i + 2 * $cur_time_diff)) -ge $RUNTIME ] && break
done
test_pass
